package com.cscd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cscd.commonutils.JwtUtils;
import com.cscd.commonutils.R;
import com.cscd.entity.User;
import com.cscd.entity.UserRole;
import com.cscd.entity.vo.UserVo;
import com.cscd.mapper.UserMapper;
import com.cscd.service.UserRoleService;
import com.cscd.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chaichai
 * @since 2024-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public R login(User user) {
        if (user.getPhone().equals("") || user.getPassword().equals("")) {
            return R.error().message("请输入账号号或密码");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User one = this.getOne(queryWrapper);
        if (one == null) {
            return R.error().message("用户不存在,请先注册");
            //添加新用户
//            User newUser = new User();
//            newUser.setPhone(user.getPhone());
//            newUser.setNickname("user_"+ RandomStringUtils.random(7,true,true));
//            newUser.setPassword(user.getPassword());
//            this.save(newUser);
//            //为用户赋予默认角色
//            UserRole userRole = new UserRole();
//            userRole.setUserId(newUser.getId());
//            userRole.setRoleId("2");
//            userRole.setRoleName("user");
//            userRoleService.save(userRole);
//            String jwtToken = JwtUtils.getJwtToken(newUser.getId(), newUser.getNickname());
//            return R.ok().data("token",jwtToken);
        } else {
            if (one.getPassword().equals(user.getPassword())) {
                String jwtToken = JwtUtils.getJwtToken(one.getId(), one.getNickname());
                return R.ok().data("token", jwtToken);
            } else {
                return R.error().message("密码错误,请确认后重新登录");
            }
        }
    }

    @Override
    public R register(User user) {
        if (StringUtils.isEmpty(user.getPhone()) || StringUtils.isEmpty(user.getPassword())) {
            return R.error().message("请输入账号号或密码");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User one = this.getOne(queryWrapper);
        if (one != null) {
            return R.error().message("用户已存在,请直接登录");
        } else {
            user.setNickname("user_" + RandomStringUtils.random(7, true, true));
            this.save(user);
            //为用户赋予默认角色
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleName("admin");
            userRole.setRoleId("1");
            userRoleService.save(userRole);
           // String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getNickname());
            return R.ok().message("注册成功");
        }
    }

    @Override
    public UserVo getUserInfo(String userId) {
        LambdaQueryWrapper<UserRole> userRoleRapper = new LambdaQueryWrapper<>();
        User user = this.getById(userId);
        userRoleRapper.eq(UserRole::getUserId,userId);
        List<UserRole> userRoles = userRoleService.list(userRoleRapper);
        UserVo userVo = new UserVo();
        userVo.setNickname(user.getNickname());
        userVo.setPhone(user.getPhone());
        userVo.setGender(user.getGender());
        ArrayList<String> roleList  = new ArrayList<>();
        userRoles.forEach(userRole -> {
            roleList.add(userRole.getRoleName());
        });
        userVo.setRoles(roleList);

        return userVo;
    }

    @Override
    public R getUserList(User user, Long pageNum, Long pageSize) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StringUtils.isEmpty(user.getPhone()),User::getPhone,user.getPhone());
        queryWrapper.eq(!StringUtils.isEmpty(user.getEmail()),User::getEmail,user.getEmail());
        queryWrapper.like(!StringUtils.isEmpty(user.getNickname()),User::getNickname,user.getNickname());
        queryWrapper.eq(!StringUtils.isEmpty(user.getGender()),User::getGender,user.getGender());
        Page<User> userPage = new Page<>(pageNum,pageSize);
        this.page(userPage,queryWrapper);
        return R.ok().data("records",userPage.getRecords()).data("total",userPage.getTotal());
    }

    @Override
    public R getUserById(String id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,id);
        User user = this.getOne(wrapper);
        return R.ok().data("user",user);
    }

    @Override
    public Boolean deleteUsers(String[] ids) {
        int count = userMapper.deleteUserByIds(ids);
        if (count>0){
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateUser(User user) {
        boolean isSave = this.updateById(user);
        return isSave;
    }

    @Override
    public Boolean addUser(User user) {
        boolean save = this.save(user);
        return save;
    }
}
